package leetcode;

import common.*;

/**
 * 两两交换链表中的节点  
 */
public class LeetCode24 {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode result = head.next;
        ListNode cur = head.next;
        ListNode prev = head;
        while (cur.next != null && cur.next.next != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev.next = next.next;
            prev = next;
            cur = next.next;
        }
        prev.next = cur.next;
        cur.next = prev;
        return result;
    }

    public static void main(String[] args) {
        LeetCode24 leetCode24 = new LeetCode24();
        System.out.println(Util.formatListNode(Util.createListNode(9)));
        System.out.println(Util.formatListNode(leetCode24.swapPairs(Util.createListNode(9))));
    }
}